float 精度问题
package main
import "fmt"
func main() {
var n float64 = 0
for i := 0; i < 1000; i++ {
n += .01
}
fmt.Println(n)
}
结果//9.999999999999831
1/3 问题
import "fmt"
import "math/big"
func main() {
z, _ := new(big.Rat).SetString("1")
three, _ := new(big.Rat).SetString("3")
x := new(big.Rat).Quo(z, three)
y := new(big.Rat).Quo(z, three)
z = z.Sub(z, x)
z = z.Sub(z, y)
s := new(big.Rat).Add(x, y)
s.Add(s, z)
fmt.Println(x.FloatString(3), "+") // 0.333
fmt.Println(y.FloatString(3), "+") // 0.333
fmt.Println(z.FloatString(3)) // 0.333
fmt.Println("=", s.FloatString(3)) // where did the other 0.001 go?
}